-module(area_server).
-behaviour(gen_server).
-compile(export_all).

% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	 terminate/2, code_change/3]).
	 
start_link() -> 
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

init([]) -> 
    process_flag(trap_exit, true),
    io:format("~p starting~n", [?MODULE]),
    {ok, 0}.

area(Thing) ->
    gen_server:call(?MODULE, {area, Thing}).
	
handle_call({area, Thing}, _From, N) -> 
    {reply, calculate_area(Thing), N + 1}.

handle_cast(_Msg, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.

terminate(_Reason, _State) -> 
    io:fwrite("~p stopping~n", [?MODULE]),
    ok.
	
code_change(_OldVsn, State, _Extra) -> {ok, State}.

calculate_area({square, X}) -> X*X;
calculate_area({rectangle, Y}) -> Y*Y.
